import * as fs from 'fs';
import * as vscode from 'vscode';
import { language } from './language';

const decoder = new TextDecoder('utf8');
export function hasFile(path: string | vscode.Uri) {
    try {
        if (typeof path !== 'string') {
            path = path.fsPath;
        }
        fs.statSync(path);
        return true;
    } catch {
        return false;
    }
}

export function getLanguage() {
    const lang = vscode.env.language.toLowerCase();
    if (lang.includes('zh')) {
        if (lang.includes('zh-cn')) {
            return 'zhs';
        } else {
            return 'zht';
        }
    } else if (lang.includes('ru')) {
        return 'ru';
    } else {
        return 'en';
    }
}

export function $r(key: string, end?: any) {
    const content = language.instance.getContent(key);
    return `${content} ${end ?? ''}`;
}

export function fileToJsonSync(path: string | vscode.Uri) {
    try {
        if (typeof path !== 'string') {
            path = path.fsPath;
        }
        const stream = fs.readFileSync(path);
        const content = decoder.decode(stream);
        return JSON.parse(content);
    } catch {
        return undefined;
    }
}